﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GCELibrary.Current;

using System.Linq.Dynamic;
using System.Linq.Expressions;
using ZF.BLL.Linq;
using ZF.BLL;
using ZF.WS.Admin;
using ZF.Model;
 

namespace ZF.BLL.Admin
{
    public class Order : ZF.BLL.Page.MMPage
    {
        public override ModuleType Module
        {
            get { return ModuleType.S_Order; }
            protected set
            {
                base.Module = value;
            }
        }
        public virtual string ListPage { get { return string.Format("{0}/shop/Orderlist.aspx", AppKey.SiteKey.ManageDirectory); } }
        public virtual string ManagePage { get { return string.Format("{0}/shop/OrderManage.aspx", AppKey.SiteKey.ManageDirectory); } }
        public virtual string CTitle { get { return "订单"; } }
    }
    public partial class OrderList : Order
    {
        /// <summary>
        /// 0全部
        /// 1待确认
        /// 2待发货
        /// 3已完成
        /// 4失效
        /// 5处理中
        /// </summary>
        [PageArgument(Key = "status", DefaultValue = 2)]
        public int Status { get; set; }

    

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                InitControls();
                View();
            }
        }
        public void InitControls()
        {

        }
        public void View()
        {
            ListBind();
        }
        /// <summary>
        /// 列表绑定
        /// </summary>
        public void ListBind()
        {
            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {

                List<Expression<Func<Model.SP_Order, bool>>> filterList = new List<Expression<Func<Model.SP_Order, bool>>>();
                IQueryable<Model.SP_Order> selector = dc.SP_Order;
                selector = selector.Where(p => !p.IsDel);

                switch (Status)
                {
                    case 1://待确认(到付）

                        selector = selector.Where(p => p.Status == (int)OrderStatus.下单10 && (p.PayType==(int)PayType.ToPay || p.PayType==(int)PayType.Bank));
                        break;
                    case 6://待确认（网付）
                        selector = selector.Where(p => p.Status == (int)OrderStatus.下单10 && p.PayType == (int)PayType.ZFB);
                        break;
                    case 2://待发货
                        selector = selector.Where(p => !p.IsSend && (((p.PayType == (int)PayType.ZFB || p.PayType == (int)PayType.Bank) && p.Status == (int)OrderStatus.确认20) || (p.IsPayed && p.PayType == (int)PayType.ZFB)));
                        selector = selector.Where(p => p.Status != (int)OrderStatus.作废50);
                        break;
                    case 3://已完成
                        selector = selector.Where(p => p.Status==(int)OrderStatus.订单已完成40);
                        break;
                    case 4://失效
                        selector = selector.Where(p => p.Status == (int)OrderStatus.作废50);
                        break;
                    case 5://处理中
                        selector = selector.Where(p => p.Status == (int)OrderStatus.处理中30);
                        break;

                }


                foreach (var filter in filterList)
                {
                    selector = selector.Where(filter);
                }


                var selWhere = selector.Select(p =>
                    new
                    {
                        Order = p,
                        Merc = p.SP_Merchandise,
                        Type = p.SP_Merchandise.Dic_MerchandiseType,
                    });
                var selPage = selWhere.Where(this.gvList).OrderBy(this.gvList.SortExpression)
                        .Skip(gvList.PageIndex * gvList.PageSize).Take(gvList.PageSize);
                this.gvList.RowCount = selWhere.Count();
                var source = selPage.ToList().Select(p => new
                {
                    Merc = p.Merc,
                    Order = p.Order,
                    Type = p.Type,
                }).ToList();
                this.gvList.DataSource = source;
                this.gvList.DataBind();

            }
        }
        /// <summary>
        /// 排序事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void gvListSorting(object sender, GridViewSortEventArgs e)
        {
            ListBind();
        }
        /// <summary>
        /// 换页事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void gvListPageChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvList.PageIndex = e.NewPageIndex;
            ListBind();
        }
        public void Delete(params int[] idArr)
        {
            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {
                bool isSuccess = true;
                try
                {
                    var list = dc.SP_Order.Where(p => idArr.Contains(p.OrderId)).ToList();
                    list.ForEach(p => p.IsDel = true);

                    dc.SubmitChanges();
                }
                catch (Exception ex)
                {
                    isSuccess = false;
                    throw SiteInfo.WarnFactory.CreateWarn(ex);
                }
                string msgKey = CTitle;
                if (isSuccess)
                    WarnFactory.CreateWarn(string.Format("删除{0}成功", msgKey), WarnIcon.Success, WarnLink.Current).Alert();

            }
        }
        public void Delete(object sender, EventArgs e)
        {
            var bc = (IButtonControl)sender;
            if (bc.CommandArgument == "select")
            {
                var idArrTemp = this.gvList.GetCheckKeys();
                if (idArrTemp.Length == 0)
                    throw SiteInfo.WarnFactory.CreateWarn("未选择任何记录");
                var idArr = idArrTemp.Select(p => p.Convert<int>()).ToArray();
                Delete(idArr);
            }
            else
            {
                Delete(bc.CommandArgument.Convert<int>());
            }
        }

        public void Affirm(object sender, EventArgs e)
        {
            var bc = (IButtonControl)sender;
            var id = bc.CommandArgument.Convert<int>();

            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {
                var order = dc.SP_Order.FirstOrDefault(p => p.OrderId == id);
                if (order == null)
                    throw WarnFactory.CreateWarn(WarnCode.ReocrdNoFind);

                if (order.Status == (int)OrderStatus.下单10)
                {
                    if (order.IsPayed || order.IsSend)
                        order.Status = (int)OrderStatus.处理中30;
                    else
                        order.Status = (int)OrderStatus.确认20;
                    dc.SubmitChanges();
                    WarnFactory.CreateWarn(new PageWarnParameter()
                    {
                        JscriptMode = true,
                        Message = "确认成功",
                        Link = WarnLink.Current,

                    }).Alert();
                }

            }

        }
        public void Rec(object sender, EventArgs e)
        {
            var bc = (IButtonControl)sender;
            var id = bc.CommandArgument.Convert<int>();

            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {
                var order = dc.SP_Order.FirstOrDefault(p => p.OrderId == id);
                if (order == null)
                    throw WarnFactory.CreateWarn(WarnCode.ReocrdNoFind);
                string msg = "";
                if (order.IsSend && order.IsPayed)
                {
                    order.Status = (int)OrderStatus.订单已完成40;
                    dc.SubmitChanges();
                    msg = "操作成功，订单已完成";
                }
                else
                {
                    if (!order.IsSend)
                        msg = "操作失败，该订单未发货";
                    else if (!order.IsPayed)
                    {
                        msg = "操作失败，该订单未支付或未设置收款信息";
                    }
                }
                WarnFactory.CreateWarn(new PageWarnParameter()
                {
                    JscriptMode = true,
                    Message = msg,
                    Link = WarnLink.Current,
                }).Alert();
            }
        }
        public void Invalid(object sender, EventArgs e)
        {
            var bc = (IButtonControl)sender;
            var id = bc.CommandArgument.Convert<int>();

            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {
                var order = dc.SP_Order.FirstOrDefault(p => p.OrderId == id);
                if (order == null)
                    throw WarnFactory.CreateWarn(WarnCode.ReocrdNoFind);
                string msg = "";
                order.Status = (int)OrderStatus.作废50;
                dc.SubmitChanges();
                msg = "操作成功，订单已作废";
                WarnFactory.CreateWarn(new PageWarnParameter()
                {
                    JscriptMode = true,
                    Message = msg,
                    Link = WarnLink.Current,
                }).Alert();
            }
        }
        public void Reduction(object sender, EventArgs e)
        {
            var bc = (LinkButton)sender;
            var id = bc.CommandArgument.Convert<int>();
            var status = 0;
            foreach (GridViewRow gvr in gvList.Rows)
            {
                var bt=gvr.FindControl(bc.ID);
                if (bt == bc)
                {
                    var ddl=(DropDownList)gvr.FindControl("ddlStatus");
                    status = ddl.SelectedValue.Convert<int>();
                }
            }
            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {
                var order = dc.SP_Order.FirstOrDefault(p => p.OrderId == id);
                if (order == null)
                    throw WarnFactory.CreateWarn(WarnCode.ReocrdNoFind);
                string msg = "";
                order.Status = status;
                dc.SubmitChanges();
                msg = "操作成功，订单已还原为" + order.StatusName;
                WarnFactory.CreateWarn(new PageWarnParameter()
                {
                    JscriptMode = true,
                    Message = msg,
                    Link = WarnLink.Current,
                }).Alert();
            }
        }
        public void Search(object sender, EventArgs e)
        {
            //this.gvList.RemoveAllFilterExpression();
            //if (this.tbTitle.Text.EmptyString() != null)
            //    this.gvList.AddFilterExpression("House.Title.Contains(@0)", this.tbTitle.Text);
            //if (this.tbHouseNo.Text.EmptyString() != null)
            //    this.gvList.AddFilterExpression("House.HouseId=@0", this.tbHouseNo.Text.Convert<int>()-10000);
            //if (this.ddlHouseType.SelectedValue != "-1")
            //    this.gvList.AddFilterExpression("House.HouseType=@0", this.ddlHouseType.SelectedValue);
            //if (this.ddlHouseStatus.SelectedValue != "-1")
            //    this.gvList.AddFilterExpression("House.Status=@0", this.ddlHouseStatus.SelectedValue.Convert<int>());
            //if (this.tbEndTime1.Text.EmptyString() != null)
            //    this.gvList.AddFilterExpression("House.AddTime<=@0", this.tbEndTime1.Text.Convert<DateTime>());
            //if (this.tbEndTime2.Text.EmptyString() != null)
            //    this.gvList.AddFilterExpression("House.AddTime>=@0", this.tbEndTime2.Text.Convert<DateTime>());

            ListBind();
        }
        public void AllList(object sender, EventArgs e)
        {
            this.gvList.RemoveAllFilterExpression();
            ListBind();
        }
        public void Oper(object sender, EventArgs e)
        {
            var bc = (IButtonControl)sender;
            var idArrTemp = this.gvList.GetCheckKeys().Select(p => p.Convert<int>()).ToArray();
            if (idArrTemp.Length == 0)
                throw SiteInfo.WarnFactory.CreateWarn("未选择任何记录");
            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {
                var list = dc.SP_Merchandise.Where(p => idArrTemp.Contains(p.MerchandiseId)).ToList();
                switch (bc.CommandArgument)
                {
                    case "SellUp":
                        list.ForEach(p =>
                        {
                            p.IsSell = true;
                            if (p.EndTime < DateTime.Now)
                                p.EndTime = DateTime.Now.AddMonths(1);

                        });
                        break;
                    case "SellDown":
                        list.ForEach(p =>
                        {
                            p.IsSell = false;
                        });
                        break;
                    case "CancelDiscount":
                        list.ForEach(p =>
                        {
                            p.Discount = 0;
                        });
                        break;
                    case "Del":
                        list.ForEach(p =>
                        {
                            p.IsDel = true;
                        });
                        break;
                    case "IsRecommend":
                        list.ForEach(p =>
                        {
                            p.IsRecommend = !p.IsRecommend;
                        });
                        break;
                }
                bool isSuccess = true;
                try
                {
                    dc.SubmitChanges();
                }
                catch (Exception ex)
                {
                    isSuccess = false;
                    throw SiteInfo.WarnFactory.CreateWarn(ex);
                }
                string msgKey = "操作";
                if (isSuccess)
                    WarnFactory.CreateWarn(string.Format("{0}成功", msgKey), WarnIcon.Success, WarnLink.Current).Alert();
            }
        }

        public string GetFreightType(int id)
        {
            return Model.FreightSet.GetNameByType(id);

        }

    }
}


